package com.hll.api.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hll.api.exception.MyException;
import com.hll.api.service.HeFengApi;
import com.hll.api.util.HttpUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * @author 何龙
 * @create 2019-06-02 12:33
 */
@Service
public class HeFengApiImpl implements HeFengApi {

	@Value("${api.hefeng.baseUrl}")
	private String baseUrl;

	@Value("${api.hefeng.userName}")
	private String userName;

	@Value("${api.hefeng.key}")
	private String secret;

	@Override
	public JSONObject liveWeather(String key, String city) {
		HashMap<String, Object> map = new HashMap<>(3);
		map.put("location", city);
		map.put("key", secret);
		String result;
		try {
			result = HttpUtils.getSSL(baseUrl + "/now", map, 0, 0);
		} catch (Exception e) {
			throw new MyException("接口访问失败");
		}
		if (StringUtils.isEmpty(result)) {
			throw new MyException("网络异常");
		}
		JSONObject jsonObject = JSON.parseObject(result);
		JSONArray heWeather5 = jsonObject.getJSONArray("HeWeather6");
		if (heWeather5.size() > 0) {
			JSONObject jsonObject1 = heWeather5.getJSONObject(0);
			return getStatus(jsonObject1);
		}
		throw new MyException("接口访问失败");
	}

	private JSONObject getStatus(JSONObject jsonObject) throws MyException {
		String status = jsonObject.getString("status");

		switch (status) {
			case "ok":
				return jsonObject;
			case "invalid key":
				throw new MyException("无效的key");
			case "invalid key type":
				throw new MyException("你输入的key不适用于当前获取数据的方式");
			case "invalid param":
				throw new MyException("无效的参数，请检查你传递的参数是否正确、完整");
			case "bad bind":
				throw new MyException("错误的绑定");
			case "no data for this location":
				throw new MyException("该城市/地区没有你所请求的数据");
			case "no more requests":
				throw new MyException("超过访问次数,明天再来访问");
			case "no balance":
				throw new MyException("没有余额，你的按量计费产品由于余额不足或欠费而不能访问，请尽快充值");
			case "too fast":
				throw new MyException("每分钟访问次数超过限定的QPM");
			case "dead":
				throw new MyException("无响应或超时");
			case "permission denied":
				throw new MyException("无访问权限，你没有购买你所访问的这部分服务");
			case "sign error":
				throw new MyException("签名错误");
			default:
				throw new MyException("未知错误");
		}

	}
}
